package cn.imvc.util;

import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics2D;
import java.awt.geom.AffineTransform;
import java.awt.image.BufferedImage;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;

public class VerifyCodeUtils {

	public static int width = 95;
	public static int height = 40;
	public static int lineCount = 2;
	public static int CodeNum = 4;

	public static Map<String, Object> createImageCode() throws Exception {
		BufferedImage img = new BufferedImage(width, height, 1);

		Color[] BCcolor = { new Color(250, 235, 215), new Color(240, 255, 255), new Color(245, 245, 245), new Color(255, 253, 205),
				new Color(200, 220, 220), new Color(240, 255, 240), new Color(250, 255, 240), new Color(255, 222, 173),
				new Color(253, 245, 230), new Color(255, 239, 213), new Color(238, 232, 170), new Color(245, 222, 179) };

		Color[] FCcolor = { new Color(65, 105, 255), new Color(106, 90, 205), new Color(56, 94, 15), new Color(8, 46, 84),
				new Color(255, 97, 0), new Color(0, 255, 0), new Color(128, 42, 42), new Color(255, 0, 0), new Color(11, 23, 70),
				new Color(25, 25, 112), new Color(255, 0, 255), new Color(176, 48, 96), new Color(0, 191, 255), new Color(0, 139, 139),
				new Color(0, 0, 0) };

		Graphics2D g = img.createGraphics();
		Random r = new Random();

		int BC = (int) Math.round(Math.random() * (BCcolor.length - 1));
		g.setColor(BCcolor[BC]);
		g.fillRect(0, 0, width, height);

		int FC = (int) Math.round(Math.random() * (FCcolor.length - 1));
		g.setColor(FCcolor[FC]);
		for (int i = 0; i < lineCount; ++i) {
			int x = r.nextInt(width);
			int y = r.nextInt(height);
			int xl = r.nextInt(12);
			int yl = r.nextInt(12);
			float thick = 3.0F;
			g.setStroke(new BasicStroke(thick, 1, 1));
			g.drawLine(x, y, (x + xl) * 2, (y + yl) * 2);
		}
		
		StringBuffer sb = new StringBuffer();
		String[] fonts = { "Courier New", "Georgia", "Time News Roman" };
		char[] ch = ToolUtils.codes.toCharArray();
		int len = ch.length;
		int fontIndex = (int) Math.round(Math.random() * (fonts.length - 1));
		StringBuffer codeSb = new StringBuffer();
		for (int i = 0; i < CodeNum; ++i) {
			int index = r.nextInt(len);

			Font f = new Font(fonts[fontIndex], 1, 30);

			AffineTransform fontAT = new AffineTransform();
			fontAT.shear(-r.nextDouble() / 9.0D, r.nextDouble() / 8.0D);
			Font fat = f.deriveFont(fontAT);
			g.setFont(fat);
			g.setTransform(fontAT);
			g.drawString(new String("" + ch[index]), i * 20 + 8, 27);
			sb.append(" " + ch[index] + " ");
			codeSb.append(ch[index]);
		}
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("code", codeSb.toString());
		map.put("img", img);
		return map;
	}
}
